package com.yoomiito.app.present.account;

import android.text.TextUtils;

import com.ali.auth.third.core.model.User;
import com.google.gson.Gson;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.Constant;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.model.bean.AppInterfaceInfo;
import com.yoomiito.app.model.bean.AreaInfo;
import com.yoomiito.app.model.bean.BingPhoneBean;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.model.order.PayResultInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.base.BaseAccountPresent;
import com.yoomiito.app.pay.PayTypeUtils;
import com.yoomiito.app.ui.account.LoginActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.wx.WXUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.http.Field;

public class LoginPresent extends BaseAccountPresent<LoginActivity> {

    private static final String TAG = "LoginPresent";
    private Disposable mDisposable;
    public LoginPresent(AppConfig appConfig) {
        super(appConfig);
    }

    /**
     * 销毁倒计时任务
     */
    public void destroyCountdownTask() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
    /**
     * 开始倒计时
     */
    public void startCountdownTask() {
        mDisposable = Flowable.intervalRange(0, 45, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> getV().CountdownTimeTask((int) (45 - aLong)))
                .doOnComplete(() -> getV().timeEndTask()).subscribe();
    }
    //发送验证码
    public void requestSendCode(String phone,String area) {
        sendCode(phone,area)
                .subscribe(new ApiSubscriber<BingPhoneBean>(handleException()) {
            @Override
            public void onSuccess(BingPhoneBean bingPhoneBean) {
                getV().showToast("发送成功");
                startCountdownTask();
                getV().dismissLoading();
            }

            @Override
            public void onFail(ApiException error) {
                if (error.getCode()==2003){
                    getV().showToast("发送失败");
                }
                getV().dismissLoading();
                XLog.d(TAG, "error ：" + "||code:" + error.getCode() + "||msg:" + error.getMsg());
            }
        });
    }

//    public void authorization_1(SHARE_MEDIA share_media) {
//        //删除微信授权
//        UMShareAPI.get(getV()).deleteOauth(getV(), SHARE_MEDIA.WEIXIN, new UMAuthListener() {
//            @Override
//            public void onStart(SHARE_MEDIA share_media) {
//                Log.i(TAG,"开始");
//            }
//
//            @Override
//            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                Log.i(TAG,"完成");
//                authorization(share_media);
//
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
//                Log.i(TAG,"错误");
//                authorization(share_media);
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA share_media, int i) {
//                Log.i(TAG,"取消");
//            }
//        });
//    }
    //授权
    public void authorization(SHARE_MEDIA share_media) {
        WXUtils.INSTANCE.wxAuthorization(getV(),share_media,(access_token, refresh_token, openid, unionid) ->
            requestUser(access_token,refresh_token,openid,unionid)
        );
    }
    //21_wHDQPMnPfPJHKf66tecTKoUDN6fFtVC_uVMMsnOqZWQK_17yaUjopWQVfP4p0o4Uv8b84NmRp0-ZHOV7ooW9UC8eM-2n2D5QuhsPxuO5D7c
    //21_4Jrk1DOQSzaqsuEu-W5y5KcdScVMUX6LnIIXiB-kyWCAmYkCfxeON-mnvpF2_Yo4_RBNXemosXb5QSu2Iet9q88-7_DAq0mBdUUHqJE2eME
    //oXOgU5vnlboNqYCW1pWUKx30Fmbw
    //ovXXe55-us85w_jiVxcMeI7UlczQ
    //验证opnid是否在后台已经注册过
    private void requestUser(String access_token, String refresh_token, String openid, String unionid) {
        getV().showLoading();
        YmApi.getYmService().verificationUser(access_token, refresh_token, openid, unionid)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel<UserInfo>>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel<UserInfo> userInfo) {
                        getV().dismissLoading();
                        if(userInfo.code == 111){
                            getV().toBindingPhoneActivity(userInfo.data);
                        }else if(userInfo.code == 200){
                            if (!TextUtils.isEmpty(userInfo.data.getToken())){
                                SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, userInfo.data.getToken());
                                getV().toMainActivity(userInfo.data);
                            }else{
                                if(TextUtils.isEmpty(userInfo.data.getParent_invitation_code())){
                                    getV().toBindInviteCode();
                                }
                            }
                        }


                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        XLog.d(TAG, "error ：" + "||code:" + error.getCode() + "||msg:" + error.getMsg());
//
                    }
                });
    }



    public void getArea() {
        YmApi.getYmService().getArea()
                .compose(getV().bindToLifecycle())
                .compose(XApi.<List<AreaInfo>>getApiTransformerData())
                .compose(XApi.<List<AreaInfo>>getScheduler())
                .subscribe(new ApiSubscriber<List<AreaInfo>>(handleException()) {
                    @Override
                    public void onSuccess(List<AreaInfo> userInfo) {
                        getV().dismissLoading();
                        getV().getArea(userInfo);

                    }//577085

                    @Override
                    public void onFail(ApiException error) {//201  跳转绑定邀请人
                        getV().dismissLoading();
                        XLog.d(TAG, "error ：" + "||code:" + error.getCode() + "||msg:" + error.getMsg());
//
                    }
                });
    }


    public void requestVerifyCode(String verify_code, String mobile, String open_id) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        getV().showLoading();
        YmApi.getYmService().verifyCode(verify_code, mobile, open_id)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<UserInfo>(handleException()) {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        getV().dismissLoading();
//                        LoginUtils.INSTANCE.loginHandle(getV(),userInfo);
                        if (!TextUtils.isEmpty(userInfo.getToken())) {
                            UserInfoConfig.putToken(userInfo.getToken());
                            getV().toMain(userInfo);//登录成功
                        } else {
                            getV().success(userInfo.binding);//需要绑定邀请码 保存Token
                        }
                    }
                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        XLog.d(TAG, "error ：" + "||code:" + error.getCode() + "||msg:" + error.getMsg());
                        if(error.getCode() == 8888){
                            getV().success("2");//需要绑定邀请码 保存Token
                        }
                    }
                });
    }


}
